﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace PPIDesktopClient.General
{
    public class DownloadFile
    {

        protected Uri m_FileUrl;
        protected FileInfo m_FileDestination;
        protected WebClient m_WebClient = new WebClient();

        public void SetUrl(string url)
        {
            m_FileUrl = new Uri(url);
        }

        public void SetFileDestination(string destinationPath)
        {
            m_FileDestination = new FileInfo(destinationPath);
        }

        public DownloadFile(string url, string destinationPath)
        :this()
        {
            m_FileUrl = new Uri(url);
            m_FileDestination = new FileInfo(destinationPath);
        }
        public DownloadFile()
        {
            m_WebClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(m_WebClient_DownloadFileCompleted);
            m_WebClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(m_WebClient_DownloadProgressChanged);

        }

        public void StartDownload()
        {

            try
            {
                m_WebClient.DownloadFileAsync(m_FileUrl, m_FileDestination.FullName);
            }
            catch (Exception ex)
            {
                
                throw;
            }
        }

        public void CancelDownload()
        {
            m_WebClient.Dispose();
        }
        
        #region WebClientEvents
        void m_WebClient_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            OnFinishDownloadFile(sender, new EventArgs());
        }
        void m_WebClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            OnProgressChanged(sender, e);
        }
        #endregion

        #region DownloadFile Events
        
        public event EventHandler FinishDownloadFile;
        public void OnFinishDownloadFile(object o, EventArgs e)
        {
            // Safely invoke an event:
            if (FinishDownloadFile != null)
            {
                FinishDownloadFile(o, e);
            }
        }

        public event EventHandler<DownloadProgressChangedEventArgs> ProgressChanged;
        private void OnProgressChanged(object o, DownloadProgressChangedEventArgs e)
        {
            // Safely invoke an event:
            if (ProgressChanged != null)
            {
                ProgressChanged(o, e);
            }
        }

        #endregion


    }
}
